package com.android.cookbook.adapter;

import java.util.ArrayList;

import com.android.cookbook.R;
import com.android.cookbook.R.drawable;
import com.android.cookbook.R.id;
import com.android.cookbook.R.layout;
import com.android.cookbook.activity.DetailDriver;
import com.android.cookbook.bean.Recipe;
import com.android.cookbook.util.Constant;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class RecipeAdapter extends ArrayAdapter {           
	
	private ArrayList<Recipe> items;           
	private Context context;
	
	public RecipeAdapter(Context context, int textViewResourceId, ArrayList<Recipe> items) {             
		super(context, textViewResourceId, items);    
		this.context = context; 
		this.items = items;
	}           
	
	@Override        
	public View getView(int position, View convertView, ViewGroup parent) {             
		View v = convertView;             
		if (v == null) {                 
			LayoutInflater vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
			v = vi.inflate(R.layout.item_list, null);             
		}             
		Recipe recipe = items.get(position);   
		EditText id_detalle = (EditText) v.findViewById(R.id.id_detail);
		if (recipe != null) {                 
			TextView name = (TextView) v.findViewById(R.id.titulo);                 
			TextView description = (TextView) v.findViewById(R.id.autor);
			ImageView image = (ImageView)v.findViewById(R.id.icon);
			
			if (name != null) {                     
				name.setText(recipe.getName());                 
			}                 
			if (description != null) {                     
				description.setText(recipe.getRectypename());                 
			}  
			if (image != null && recipe.getImage() != null) {      
				
				image.setImageResource(Integer.parseInt(recipe.getImage()));
			}else{
				image.setImageResource(R.drawable.icon);
			}
		} 
		
		ImageView itemImage = (ImageView) v.findViewById(R.id.icon);
		if (id_detalle != null) {
			itemImage.setTag(String.valueOf(recipe.get_id()));
		}
        
		itemImage.setOnClickListener(new View.OnClickListener() {             
        	public void onClick(View view) {                   
        		Bundle bundle = new Bundle();
        		String id_detail = (String)view.getTag();
        		bundle.putString(Constant.TYPE_ID,id_detail);
        		Intent myIntent = new Intent(view.getContext(),DetailDriver.class);
        		myIntent.putExtras(bundle);                   
        		context.startActivity(myIntent);            
        	}          
        }); 

		return v;         
	}     




}